package eproject.mm.com.projectsupervision.service;

import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import java.io.File;

import eproject.mm.com.projectsupervision.PrjApplication;

/**
 * Created by momotea on 17-8-4.
 */

public class DownloadService extends Service {
   String sOldName="";


    public DownloadService() {
    }

    /**
     * 安卓系统下载类
     **/
    DownloadManager manager;

    /**
     * 接收下载完的广播
     **/
    DownloadService.DownloadCompleteReceiver receiver;


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Bundle bundle = intent.getExtras();
        String urlPath= bundle.getString("urlPath");
        String oldname= bundle.getString("oldname");
        sOldName=oldname;

        // 调用下载
        initDownManager(urlPath);

        return super.onStartCommand(intent, flags, startId);
    }


    /**
     * 初始化下载器
     **/
    private void initDownManager(String urlPath) {

        manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

        if (receiver == null) {
            receiver = new DownloadCompleteReceiver();
        } else {
            unregisterReceiver(receiver);
            receiver = new DownloadCompleteReceiver();
        }

        //设置下载地址

        Uri parse = Uri.parse(urlPath);
        DownloadManager.Request down = new DownloadManager.Request(parse);

        // 设置允许使用的网络类型，这里是移动网络和wifi都可以
        down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);

        down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE | DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        down.setTitle(sOldName);
        down.setDescription("正在下载文件...");
        Toast.makeText(PrjApplication.getInstance(),"正在下载...",Toast.LENGTH_SHORT).show();

        down.setDestinationInExternalPublicDir("cloud8", sOldName);//存到文件夹cloud  文件名为sOldName


        // 显示下载界面
        down.setVisibleInDownloadsUi(true);

        // 设置下载文件的保存位置
        File saveFile = new File(Environment.getExternalStorageDirectory(), sOldName);
        down.setDestinationUri(Uri.fromFile(saveFile));

        // 将下载请求放入队列
        manager.enqueue(down);

        //注册下载广播
        try {
            registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        } catch (Exception e) {
            Log.e(this.getClass().getName(), e.toString());
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub

        return null;
    }

    @Override
    public void onDestroy() {

        // 注销下载广播
        if (receiver != null)
            unregisterReceiver(receiver);

        super.onDestroy();
    }

    // 接受下载完成后的intent
    class DownloadCompleteReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            DownloadManager manager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);

                //判断是否下载完成的广播
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {

                //获取下载的文件id
                long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downId);
                Cursor c = manager.query(query);
                if (!c.moveToFirst()) {
                    c.close();
                    return;
                }
                    // 下载请求的状态
                    int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
                    /*
                     * 判断是否下载成功，其中状态 status 的值有 5 种:
                     *     DownloadManager.STATUS_SUCCESSFUL:   下载成功
                     *     DownloadManager.STATUS_FAILED:       下载失败
                     *     DownloadManager.STATUS_PENDING:      等待下载
                     *     DownloadManager.STATUS_RUNNING:      正在下载
                     *     DownloadManager.STATUS_PAUSED:       下载暂停
                     */
                if (status == DownloadManager.STATUS_SUCCESSFUL) {
                    Toast.makeText(PrjApplication.getInstance(),"下载成功",Toast.LENGTH_SHORT).show();
                }else  if (status == DownloadManager.STATUS_FAILED) {
                    Toast.makeText(PrjApplication.getInstance(),"下载失败",Toast.LENGTH_SHORT).show();
                }else  if (status == DownloadManager.STATUS_PENDING) {
                    Toast.makeText(PrjApplication.getInstance(),"等待下载",Toast.LENGTH_SHORT).show();
                }else  if (status == DownloadManager.STATUS_RUNNING) {
                    Toast.makeText(PrjApplication.getInstance(),"正在下载",Toast.LENGTH_SHORT).show();
                }else  if (status == DownloadManager.STATUS_PAUSED) {
                    Toast.makeText(PrjApplication.getInstance(),"下载暂停",Toast.LENGTH_SHORT).show();
                }

                //获取文件下载路径
                    String filePath = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                     c.close();
                    //如果文件名不为空，说明已经存在了
                    if(filePath != null){
                        openFiles(filePath);
                    }

            }else if(DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(intent.getAction())){
                long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
                //点击通知栏取消下载
                manager.remove(ids);
                Toast.makeText(PrjApplication.getInstance(),"已经取消下载",Toast.LENGTH_SHORT);

                //停止服务并关闭广播
                DownloadService.this.stopSelf();

            }
        }
    }

    //打开文件时调用
    public void openFiles(String filesPath) {
        Uri uri = Uri.parse("file://" + filesPath);
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);

        String type = getMIMEType(filesPath);
        intent.setDataAndType(uri, type);
        if (!type.equals("*/*")) {
            try {
                startActivity(intent);
            } catch (Exception e) {
                startActivity(showOpenTypeDialog(filesPath));
            }
        } else {
            startActivity(showOpenTypeDialog(filesPath));
        }
    }

    //显示打开方式
    public void show(String filesPath){
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        startActivity(showOpenTypeDialog(filesPath));
    }

    public static Intent showOpenTypeDialog(String param) {
        Log.e("ViChildError", "showOpenTypeDialog");
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "*/*");
        return intent;
    }

    /**
     * --获取文件类型 --
     */
    public static String getMIMEType(String filePath) {
        String type = "*/*";
        String fName = filePath;

        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        }

        String end = fName.substring(dotIndex, fName.length()).toLowerCase();
        if (end == "") {
            return type;
        }

        for (int i = 0; i < MIME_MapTable.length; i++) {
            if (end.equals(MIME_MapTable[i][0])) {
                type = MIME_MapTable[i][1];
            }
        }
        return type;
    }

    /**
     * -- MIME 列表 --
     */
    public static final String[][] MIME_MapTable =
            {
                    // --{后缀名， MIME类型}   --
                    {".doc", "application/msword"},
                    {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" },
                    {".gif", "image/gif"},
                    {".jpeg", "image/jpeg"},
                    {".jpg", "image/jpeg"},
                    {".pdf", "application/pdf"},
                    {".png", "image/png"},
                    {".ppt", "application/vnd.ms-powerpoint"},
                    {".pqf", "application/x-cprplayer"},
                    {".xls", "application/vnd.ms-excel"},
                    {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },
                    {"", "*/*"}
            };
    }